import axios from 'axios';

const userinfo = JSON.parse(localStorage.getItem('userinfo')) || {
  token:'',
  role:'',
  username:'',
  balance:0
}

const login = (data) => {
  return axios.post('/api/login',data).then(res => {
    console.log(res.data.data);
    return res.data.data;
  });
}
export default {
  namespace:'user',
  state:userinfo,
  effects:{
    *login(action,{call,put}){
      try {
        const result = yield call(login,action.payload)//异步请求
        //登录成功
        alert('登录成功');
        localStorage.setItem('userinfo',JSON.stringify(result));//序列化进本地存储
        yield put({type:'init',payload:result});//状态更新
      } catch (error) {
        console.log('登录失败',error);
      }
    }
  },
  reducers:{
    init(state,action){
      return action.payload;
    }
  }
}